//
//  TypeSegmentVM.swift
//  kxf
//
//  Created by Mac on 2024/3/9.
//

import Foundation
import UIKit

class TypeSegmentVM: UIView {
    
    let selfWidth = kFitWidth(216)
    let selfHeight = kFitWidth(48)
    
    var leftTapBlock:(()->())?
    var rightTapBlock:(()->())?
    
    var tapIndex = 1

    override init(frame:CGRect){
        super.init(frame: CGRect.init(x: frame.origin.x, y: frame.origin.y, width: selfWidth, height: selfHeight))
        self.backgroundColor = .clear
        self.isUserInteractionEnabled = true
        self.layer.cornerRadius = kFitWidth(24)
        self.clipsToBounds = true
        
        initUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    lazy var leftButton : UIButton = {
        let btn = UIButton()
        btn.frame = CGRect.init(x: 0, y: 0, width: kFitWidth(108), height: kFitWidth(48))
        btn.setBackgroundImage(UIImage.init(named: "segment_left_btn_normal"), for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "segment_left_btn_selected"), for: .selected)
        btn.setTitle("邀请商户", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.setTitleColor(.white, for: .selected)
        btn.isSelected = true
        btn.titleLabel?.font = .systemFont(ofSize: 18, weight: .medium)
        
        btn.addTarget(self, action: #selector(leftTapAction), for: .touchUpInside)
        
        return btn
    }()
    lazy var rightButton : UIButton = {
        let btn = UIButton()
        btn.frame = CGRect.init(x: kFitWidth(108), y: 0, width: kFitWidth(108), height: kFitWidth(48))
        btn.setBackgroundImage(UIImage.init(named: "segment_right_btn_normal"), for: .normal)
        btn.setBackgroundImage(UIImage.init(named: "segment_right_btn_selected"), for: .selected)
        btn.setTitle("邀请服务商", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.setTitleColor(.white, for: .selected)
        btn.titleLabel?.font = .systemFont(ofSize: 18, weight: .medium)
        
        btn.addTarget(self, action: #selector(rightTapAction), for: .touchUpInside)
        
        return btn
    }()
}

extension TypeSegmentVM{
    @objc func leftTapAction() {
        if tapIndex == 1{
            return
        }
        tapIndex = 1
        self.leftButton.isSelected = true
        self.rightButton.isSelected = false
        if self.leftTapBlock != nil{
            self.leftTapBlock!()
        }
    }
    @objc func rightTapAction() {
        if tapIndex == 2{
            return
        }
        tapIndex = 2
        self.leftButton.isSelected = false
        self.rightButton.isSelected = true
        if self.rightTapBlock != nil{
            self.rightTapBlock!()
        }
    }
}

extension TypeSegmentVM{
    func initUI() {
        addSubview(leftButton)
        addSubview(rightButton)
    }
}
